package cn.iclass.modules.sys.controller;

import cn.hutool.captcha.ICaptcha;
import cn.hutool.core.io.IoUtil;
import cn.iclass.common.utils.Result;
import cn.iclass.modules.sys.entity.SysUserEntity;
import cn.iclass.modules.sys.model.form.SysLoginForm;
import cn.iclass.modules.sys.service.SysCaptchaService;
import cn.iclass.modules.sys.service.SysUserService;
import cn.iclass.modules.sys.service.SysUserTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录相关
 *
 * @author alan
 * @date 2016年11月10日 下午1:15:31
 */
@RestController
@Api("登录相关")
public class SysLoginController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private SysCaptchaService sysCaptchaService;

	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	@ApiOperation("验证码")
	public void captcha(HttpServletResponse response, String uuid) throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		ICaptcha captcha = sysCaptchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		captcha.write(out);
		IoUtil.close(out);
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	@ApiOperation("登录")
	public Result login(@RequestBody SysLoginForm form) {
		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		if (!captcha) {
			return Result.error("验证码不正确");
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if (user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return Result.error("账号或密码不正确");
		}

		//生成token，并保存到数据库
		return sysUserTokenService.createToken(user.getUserId());
	}


	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	@ApiOperation("退出")
	public Result logout(HttpServletRequest httpRequest) {

		//从header中获取token
		String token = httpRequest.getHeader("token");

		//如果header中不存在token，则从参数中获取token
		if (StringUtils.isBlank(token)) {
			token = httpRequest.getParameter("token");
		}
		sysUserTokenService.logout(token);
		return Result.ok();
	}

}
